<template>
  <div class="file-tree">
    <ul>
      <li v-for="item in data" :key="item.name">
        <div v-if="item.children" @click="toggle(item)" class="folder" :class="{ expanded: item.expanded }">
          <span class="arrow" :class="{ expanded: item.expanded }"></span>
          <span>{{ item.name }}</span>
        </div>
        <div v-else @click="onFileSelected(item)" class="file" :class="{ selected: selectedItem === item }">
          <span>{{ item.name }}</span>
        </div>
        <ul v-if="item.children && item.expanded" class="children">
          <FileTree :data="item.children" @fileSelected="onFileSelected" :parent="item" />
        </ul>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, ref } from 'vue';

const props = defineProps({
  data: Array,
  parent: Object, // 传递父节点
});

const emit = defineEmits(['fileSelected']);

const selectedItem = ref(null);

const toggle = (item) => {
  item.expanded = !item.expanded;
};

const onFileSelected = (file) => {
  // 重置选中的文件
  selectedItem.value = null;

  // 更新选中的文件
  selectedItem.value = file;

  emit('fileSelected', file);
};
</script>

<style scoped>
.file-tree ul {
  list-style-type: none;
  padding-left: 10px;
}

.folder {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.arrow {
  margin-right: 5px;
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid black;
  transition: transform 0.3s ease;
}

.arrow.expanded {
  transform: rotate(90deg);
}

.children {
  margin-left: 10px;
}

.file {
  cursor: pointer;
  padding-left: 15px; /* 与文件夹对齐 */
}

.file.selected {
  background-color: #d3d3d3; /* 选中的文件背景色 */
}
</style>
